package cn.x.functions;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.functions.AbstractFunction;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jmeter.util.JMeterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
 * @author a tester
 * @date 2021/5/22
 */
public class ARandomString2 extends AbstractFunction {

    private static final Logger log = LoggerFactory.getLogger(ARandomString2.class);

    private static final List<String> desc = new ArrayList<>();

    private static final String KEY = "__ARandomString2"; //$NON-NLS-1$

    /**
     * 参数一：长度
     * 参数二：数字\字母\大写字母\小写字母\全部
     * 参数二：存储的变量名
     */
    static {
        desc.add("长度"); //$NON-NLS-1$
        desc.add("数字\\字母\\大写字母\\小写字母\\全部"); //$NON-NLS-1$
        desc.add(JMeterUtils.getResString("function_name_paropt")); //$NON-NLS-1$
    }


    private static final int MAX_PARAM_COUNT = 3;

    private CompoundVariable[] values;

    private static final int MIN_PARAM_COUNT = 0;

    private static final int LENGTH = 1;

    private static final int TYPE = 2;

    private static final int PARAM_NAME = 3;


    /**
     * No-arg constructor.
     */
    public ARandomString2() {
        super();
    }

    /** {@inheritDoc} */
    @Override
    public String execute(SampleResult previousResult, Sampler currentSampler)
            throws InvalidVariableException {

        int length = 10;
        if (values.length >= LENGTH) {
            String values1 = values[LENGTH - 1].execute().trim();
            if(StringUtils.isNotBlank(values1)){
                try {
                    length = Integer.parseInt(values1);
                }catch (NumberFormatException e){
                    log.error("{}",e);
                }
            }
        }

        String type = "";//means no restriction
        if (values.length >= TYPE) {
            type = values[TYPE - 1].execute().trim();
        }

        String myName = "";//$NON-NLS-1$
        if (values.length >= PARAM_NAME) {
            myName = values[PARAM_NAME - 1].execute().trim();
        }

        String myValue = "";

        switch(type){
            case "数字": myValue = RandomStringUtils.randomNumeric(length);break;
            case "字母": myValue = RandomStringUtils.randomAlphabetic(length);break;
            case "大写字母": myValue = RandomStringUtils.randomAlphabetic(length).toUpperCase();break;
            case "小写字母": myValue = RandomStringUtils.randomAlphabetic(length).toLowerCase();break;
            default: myValue = RandomStringUtils.randomAlphanumeric(length);
        }

        if (myName.length() > 0) {
            JMeterVariables vars = getVariables();
            if (vars != null) {// Can be null if called from Config item testEnded() method
                vars.put(myName, myValue);
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("{} name:{} value:{}", Thread.currentThread().getName(), myName, myValue); //$NON-NLS-1$
        }

        return myValue;
    }

    /** {@inheritDoc} */
    @Override
    public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
        checkParameterCount(parameters, MIN_PARAM_COUNT, MAX_PARAM_COUNT);
        values = parameters.toArray(new CompoundVariable[parameters.size()]);
    }

    /** {@inheritDoc} */
    @Override
    public String getReferenceKey() {
        return KEY;
    }

    /** {@inheritDoc} */
    @Override
    public List<String> getArgumentDesc() {
        return desc;
    }
}